package utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lwq
 * @ClassName PdfUtils.java
 * @Description //TODO $
 * @createTime 2023-05-15 09:48
 */
@Slf4j
public class PdfUtils {

    private static byte[] mergePdfFiles(List<InputStream> inputStreams, String outFile) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Document document = new Document();// 创建一个新的PDF
        byte[] pdfs = new byte[0];
        try {
            PdfCopy copy = new PdfCopy(document, bos);
            document.open();
            for (InputStream is : inputStreams) {// 取出单个PDF的数据
                PdfReader reader = new PdfReader(stream2Byte(is));
                int pageTotal = reader.getNumberOfPages();
                for (int pageNo = 1; pageNo <= pageTotal; pageNo++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, pageNo);
                    copy.addPage(page);
                }
                reader.close();
            }
            document.close();
            pdfs = bos.toByteArray();
            bos.close();
            copy.close();
            FileCopyUtils.copy(pdfs, new File(outFile));
        } catch (DocumentException | IOException e) {
            log.error("合并PDF出错：" + e);
        }
        return pdfs;
    }

    private static byte[] stream2Byte(InputStream inputStream) {
        byte[] buffer = new byte[0];
        try (InputStream fis = inputStream; ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            buffer = bos.toByteArray();
        } catch (IOException e) {
        }
        return buffer;
    }

    public static void main(String[] args) {
        List<InputStream> inputPdfList = new ArrayList<InputStream>();
        try {
            inputPdfList.add(new FileInputStream("/Users/c7/Desktop/test.pdf"));
            inputPdfList.add(new FileInputStream("/Users/c7/Desktop/test1.pdf"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        mergePdfFiles(inputPdfList,"/Users/c7/Desktop/test2.pdf");
    }
}
